package app.models.member;

import app.Const;
import app.dtos.IntegralType;
import app.kit.CommonKit;
import app.kit.TypeKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import goja.StringPool;
import goja.annotation.TableBind;
import goja.date.DateFormatter;
import goja.plugins.sqlinxml.SqlKit;
import goja.tuples.Pair;
import org.joda.time.DateTime;

import java.util.List;

import static goja.StringPool.EMPTY;

/**
 * <p>
 * The database RLM_INTEGRAL_RECORDS Model.
 * 积分流水纪录
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
@TableBind(tableName = "rlm_integral_records")
public class IntegralRecord extends Model<IntegralRecord> {

    /**
     * The public dao.
     */
    public static final IntegralRecord dao = new IntegralRecord();


    private static final long serialVersionUID = -5984151300691108384L;

    public List<IntegralRecord> findByMember(String m_id) {
        return find(SqlKit.sql("integralrecord.findByMember"), m_id);
    }

    /**
     * 积分增加
     *
     * @param record_time 记录日期
     * @param member      会员
     * @param type        类型说明
     * @param earning     收入积分
     * @param balance     余额积分
     * @return 是否纪录成功
     */
    public boolean earning(DateTime record_time, int member, IntegralType type, String remark, int earning, int balance) {
        DateTime now = DateTime.now();
        IntegralRecord integralRecord = new IntegralRecord();
        integralRecord.set(Const.FIELD_MEMBER, member);
        integralRecord.set("record_year", record_time.getYear());
        integralRecord.set("record_month", record_time.getMonthOfYear());
        integralRecord.set("record_day", record_time.getDayOfMonth());
        integralRecord.set("record_time", record_time);
        integralRecord.set(Const.FIELD_TYPE, type.toString());
        integralRecord.set("earning", earning);
        integralRecord.set("balance", balance);
        integralRecord.set("remark", remark);
        integralRecord.set(Const.FIELD_CREATE_TIME, now);
        return integralRecord.save();
    }

    /**
     * 积分支出
     *
     * @param record_time 记录日期
     * @param member      会员
     * @param remark      支出说明
     * @param expense     支出积分
     * @param balance     余额积分
     * @return 是否纪录成功
     */
    public boolean expense(DateTime record_time, int member, String remark, int expense, int balance) {
        DateTime now = DateTime.now();
        IntegralRecord integralRecord = new IntegralRecord();
        integralRecord.set(Const.FIELD_MEMBER, member);
        integralRecord.set("record_year", record_time.getYear());
        integralRecord.set("record_month", record_time.getMonthOfYear());
        integralRecord.set("record_day", record_time.getDayOfMonth());
        integralRecord.set("record_time", record_time);
        integralRecord.set("remark", remark);
        integralRecord.set("expense", expense);
        integralRecord.set("balance", balance);
        integralRecord.set(Const.FIELD_CREATE_TIME, now);
        return integralRecord.save();
    }


    /**
     * 检查系统是否今日已经奖励了会员登录积分
     *
     * @param today        日前
     * @param member       会员
     * @param integralType 积分类型
     * @return 如果没有奖励则返回true
     */
    public boolean checkToday(DateTime today, int member, IntegralType integralType) {
        IntegralRecord record = findFirst(SqlKit.sql("integralrecord.checkToday"), member, integralType.toString(),
                today.getYear(), today.getMonthOfYear(), today.getDayOfMonth());
        return record == null || record.getNumber(Const.FIELD_CNT).intValue() <= 0;
    }

    /**
     * 同过会员，时间类型，分页，类型查询帐号记录
     *
     * @param memberId 会员ID
     * @param timeType 1：三个月，2：半年
     * @param page     当前页
     * @param pageSize 分页大小
     * @param type     0：表示全部，1：表示支出，2：收入
     *                 timeType 1：三个月，2：半年
     *                 type 0：表示全部，1：表示支出，2：收入
     */
    public Page<IntegralRecord> findByMemerbTimeType(int memberId, int timeType, int page, int pageSize, int type) {
        Pair<Integer, Integer> offsets = CommonKit.pageOffset(page, pageSize);
        DateTime now = DateTime.now();
        DateTime month_time;
        int total = 0;
        int totalPage;
        List<IntegralRecord> integralRecords = null;
        month_time = now.plusMonths((timeType == 1) ? -3 : -6);
        String lastT = month_time.toString(DateFormatter.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        String countByMembertimeType = SqlKit.sql("integralrecord.findCountByMemerbTimeType");
        IntegralRecord integralRecord;
        String tpl_time_member = SqlKit.sql("integralrecord.findByMemerbTimeType");
        switch (type) {
            case 0:
                integralRecord = findFirst(String.format(countByMembertimeType, EMPTY), memberId, lastT);
                total = TypeKit.getInt(integralRecord, Const.FIELD_CNT);
                integralRecords = find(String.format(tpl_time_member, StringPool.EMPTY), memberId, lastT, offsets.getValue1(), offsets.getValue0());
                break;
            case 1:
                integralRecord = findFirst(String.format(countByMembertimeType, " AND earning =? "), memberId, lastT, 0);
                total = TypeKit.getInt(integralRecord, Const.FIELD_CNT);
                integralRecords = find(String.format(tpl_time_member, " AND earning =? "), memberId, lastT, 0, offsets.getValue1(), offsets.getValue0());
                break;
            case 2:
                integralRecord = findFirst(String.format(countByMembertimeType, " AND expense =? "), memberId, lastT, 0);
                total = TypeKit.getInt(integralRecord, Const.FIELD_CNT);
                integralRecords = find(String.format(tpl_time_member, " AND expense =? "), memberId, lastT, 0, offsets.getValue1(), offsets.getValue0());
                break;
        }
        if (total % pageSize != 0) {
            totalPage = total / pageSize + 1;
        } else {
            totalPage = total / pageSize;
        }
        return new Page<IntegralRecord>(integralRecords, page, pageSize, totalPage, total);
    }
}